package com.nbjtjc.safe.util;

import cn.hutool.core.util.ImageUtil;
import com.nbjtjc.safe.model.sys.SysFile;
import net.coobird.thumbnailator.Thumbnails;
import net.coobird.thumbnailator.util.ThumbnailatorUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.*;
import java.time.LocalDate;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

@Component
public class FileUtil {

    @Value("${file.path.prefix}")
    private String filePrefix;

    public static void main(String[] args) throws IOException {
        String fileName="dada.jpg";
        String fileType=fileName.substring(fileName.lastIndexOf(".")+1,fileName.length());
        System.out.println(fileType);
        File jpg=new File("d://suofang.jpg");
        File jpg1=new File("d://suofang1.jpg");
        Thumbnails.of(jpg).scale(0.25).toFile(jpg1);
    }
    public  String  getFilePath(){
        LocalDate localDate=LocalDate.now();
        int year=localDate.getYear();
        int month=localDate.getMonthValue();
        int day=localDate.getDayOfMonth();
        System.out.println(year+"-"+month+"-"+day);
        return filePrefix+"/"+year+"/"+month+"/"+day+"/";
    }

    public  String getFileType(SysFile sysFile){
        String fileName=sysFile.getFileName();
        String fileType=fileName.substring(fileName.lastIndexOf(".")+1,fileName.length());
        return fileType;
    }
    public  String  getFilePath(String prefix){
        LocalDate localDate=LocalDate.now();
        int year=localDate.getYear();
        int month=localDate.getMonthValue();
        int day=localDate.getDayOfMonth();
        System.out.println(year+"-"+month+"-"+day);
        return prefix+"/"+year+"/"+month+"/"+day+"/";
    }

    /**
     * 文件夹获取，加入时间戳保证唯一性
     * @param prefix
     * @return
     */
    public String getFilePathTime(String prefix){
        LocalDate localDate=LocalDate.now();
        int year=localDate.getYear();
        int month=localDate.getMonthValue();
        int day=localDate.getDayOfMonth();
        System.out.println(year+"-"+month+"-"+day);
        return prefix+"/"+year+"/"+month+"/"+day+"/"+System.currentTimeMillis()+"/";
    }



    public File  convertPng2Jpg(MultipartFile file) throws IOException {
        String pngReg=".+(.PNG|.png)$";
        if( Pattern.compile(pngReg).matcher(file.getOriginalFilename()).find()){
            File targetFile=new File(getFilePath()+file.getOriginalFilename()
                    .toLowerCase().replace(".png",".jpg"));
            FileOutputStream fileOutputStream=new FileOutputStream(targetFile);
            ImageUtil.convert(file.getInputStream(),ImageUtil
                    .IMAGE_TYPE_JPG,fileOutputStream);
            return targetFile;
        }
        throw new FileNotFoundException("png 转jpg时文件未找到，或者格式不是png");
    }
    public File getFile(SysFile file){
        String filePath=file.getPath()+file.getFileName();
        String reg = ".+(.JPEG|.jpeg|.JPG|.jpg|.PNG|.png)$";
        Pattern pattern = Pattern.compile(reg);
        Matcher matcher = pattern.matcher(file.getFileName());
        if (matcher.find()&&!file.getPercentage().equals(1)) {//文件是图片或者压缩比是1

            String targetFilePath = file.getPath()+file.getFileName()
                    .substring(0, file.getFileName().lastIndexOf('.'))
                    +'_'+(int)(file.getPercentage()*100)+ file.getFileName()
                    .substring(file.getFileName().lastIndexOf('.'), file.getFileName().length());

            File targetFile=new File(targetFilePath);
            if(!targetFile.exists()){//压缩文件不存在
                targetFile=new File(filePath);
            }
            return targetFile;
        }else{//文件为非图片
            File targetFile=new File(file.getPath());
            return targetFile;
        }

    }


    /**
     * 下载文件
     * @param response
     * @param file
     * @throws FileNotFoundException
     */
    public void writeFile(HttpServletResponse response,File file) throws FileNotFoundException {
        if (file != null) {
            BufferedInputStream bis = null;
            byte[] buff = new byte[1024];
            response.setDateHeader("Expires", 0);
            response.setHeader("Cache-Control", "no-store, no-cache, must-revalidate");
            response.addHeader("Cache-Control", "post-check=0, pre-check=0");
            response.setHeader("Pragma", "no-cache");
            response.setContentType("image/jpeg");
               response.setHeader("Content-Disposition", "attachment;filename=" + file.getName());
            try (ServletOutputStream outputStream = response.getOutputStream()) {
                bis = new BufferedInputStream(new FileInputStream(file));
                int i = bis.read(buff);
                while (i != -1) {
                    outputStream.write(buff, 0, i);
                    outputStream.flush();
                    i = bis.read(buff);
                } 
            } catch (IOException e) {
                throw new FileNotFoundException("输出文件时报错：" + e.getMessage());
            } finally {
                if (bis != null) {
                    try {
                        bis.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
        } else {
            throw new FileNotFoundException("文件没有找到");
        }
    }

    public void writeFile(HttpServletResponse response,InputStream inputStream) throws FileNotFoundException {
        if (inputStream != null) {
            BufferedInputStream bis = null;
            byte[] buff = new byte[1024];
            response.setDateHeader("Expires", 0);
            response.setHeader("Cache-Control", "no-store, no-cache, must-revalidate");
            response.addHeader("Cache-Control", "post-check=0, pre-check=0");
            response.setHeader("Pragma", "no-cache");
            response.setContentType("image/jpeg");
            response.setHeader("Content-Disposition", "attachment;filename=processPic" );
            try (ServletOutputStream outputStream = response.getOutputStream()) {
                bis = new BufferedInputStream(inputStream);
                int i = bis.read(buff);
                while (i != -1) {
                    outputStream.write(buff, 0, i);
                    outputStream.flush();
                    i = bis.read(buff);
                }
            } catch (IOException e) {
                throw new FileNotFoundException("输出文件时报错：" + e.getMessage());
            } finally {
                if (bis != null) {
                    try {
                        bis.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
        } else {
            throw new FileNotFoundException("文件没有找到");
        }
    }
}
